package com.fbee.smartcommunities.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fbee.smartcommunities.entity.RoleUser;
import com.fbee.smartcommunities.entity.User;
import com.fbee.smartcommunities.mapper.RoleUserMapper;
import com.fbee.smartcommunities.service.RoleUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fbee.smartcommunities.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 汪佳泉
 * @since 2024-08-17
 */
@Service
public class RoleUserServiceImpl extends ServiceImpl<RoleUserMapper, RoleUser> implements RoleUserService {

    @Resource
    private UserService userService;

    @Override
    @Transactional
    public Boolean save(Long roleId, Long[] userIds) {
        this.remove(new QueryWrapper<RoleUser>().eq("role_id",roleId));
        List<RoleUser> roleUsers = new ArrayList<>();
        for (Long userId : userIds) {
            roleUsers.add(new RoleUser(roleId, userId));
            // 同时将user表中的role_id也更新一下
            userService.update(new UpdateWrapper<User>().set("role_id", roleId).eq("id", userId));
        }
        return this.saveBatch(roleUsers);
    }

}
